package com.yww.leetcode2.stack_queue;

import java.util.Stack;

/**
 * @author yww
 * @description 20. 有效的括号
 * @since 2024/11/20
 */
public class IsValid20_03 {
    public boolean isValid(String s) {
        if (s.length() % 2 != 0) {
            return false;
        }
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '(') {
                stack.push(')');
            } else if (c == '{') {
                stack.push('}');
            } else if (c == '[') {
                stack.push(']');
            } else if (!stack.isEmpty() && stack.peek() != c) { // 出现右括号的情况
                return false;
            } else if (stack.isEmpty()) {
                return false;
            } else {
                stack.pop();
            }
        }
        return stack.isEmpty();
    }
}
